


// 对Date的扩展，将 Date 转化为指定格式的String   
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，   
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)   
// 例子：   
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423   
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18   
Date.prototype.format = function(fmt)   
{ //author: meizz   
  var o = {   
    "M+" : this.getMonth()+1,                 //月份   
    "d+" : this.getDate(),                    //日   
    "h+" : this.getHours(),                   //小时   
    "m+" : this.getMinutes(),                 //分   
    "s+" : this.getSeconds(),                 //秒   
    "q+" : Math.floor((this.getMonth()+3)/3), //季度   
    "S"  : this.getMilliseconds()             //毫秒   
  };   
  if(/(y+)/.test(fmt))   
    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));   
  for(var k in o)   
    if(new RegExp("("+ k +")").test(fmt))   
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));   
  return fmt;   
}


/***
 * 通过yyyy-MM-dd hh:mm:ss这格式的字符串转换为日期
 */
function dateFromStr(pvStrDt){
	pvStrDt = pvStrDt.replace(/-/g,"/");
	return new Date(pvStrDt );
}
Array.prototype.indexOf = function(val) {
	for (var i = 0; i < this.length; i++) {
		if (this[i] == val)
			return i;
	}
	return -1;
};
Array.prototype.remove = function(val) {
   if (typeof this.indexOf=="undefined") return;
	var index = this.indexOf(val);
	if (index > -1) {
		this.splice(index, 1);
	}
};
if (!Array.prototype.includes) {
	  Array.prototype.includes = function(searchElement /*, fromIndex*/) {
	    'use strict';
	    if (this == null) {
	      throw new TypeError('Array.prototype.includes called on null or undefined');
	    }

	    var O = Object(this);
	    var len = parseInt(O.length, 10) || 0;
	    if (len === 0) {
	      return false;
	    }
	    var n = parseInt(arguments[1], 10) || 0;
	    var k;
	    if (n >= 0) {
	      k = n;
	    } else {
	      k = len + n;
	      if (k < 0) {k = 0;}
	    }
	    var currentElement;
	    while (k < len) {
	      currentElement = O[k];
	      if (searchElement === currentElement ||
	         (searchElement !== searchElement && currentElement !== currentElement)) { // NaN !== NaN
	        return true;
	      }
	      k++;
	    }
	    return false;
	  };
	}

if(typeof String.prototype.trim !== 'function') {
    String.prototype.trim = function() {
        return this.replace(/^\s+|\s+$/g, ''); 
    }
}
if (typeof String.prototype.startsWith != 'function') {
	 String.prototype.startsWith = function (prefix){
	  return this.slice(0, prefix.length) === prefix;
	 };
}

if (typeof String.prototype.endsWith != 'function') {
	 String.prototype.endsWith = function(suffix) {
	  return this.indexOf(suffix, this.length - suffix.length) !== -1;
	 };
}
<!-- lang: js -->
/**
 * 替换所有匹配exp的字符串为指定字符串
 * @param exp 被替换部分的正则
 * @param newStr 替换成的字符串
 */
String.prototype.replaceAll = function (exp, newStr) {
    return this.replace(new RegExp(exp, "gm"), newStr);
};

/**
 * 原型：字符串格式化
 * @param args 格式化参数值
 */
String.prototype.format = function(args) {
    var result = this;
    if (arguments.length < 1) {
        return result;
    }

    var data = arguments; // 如果模板参数是数组
    if (arguments.length == 1 && typeof (args) == "object") {
        // 如果模板参数是对象
        data = args;    
	    for ( var key in data) {
	        var value = data[key];
	        if (undefined != value) {
	            result = result.replaceAll("\\{" + key + "\\}", value);
	        }
	    }
    }
    else{
    	   
	    for ( var i=0;i<arguments.length;i++){
	        var value = arguments[i];
	        if (undefined != value) {
	            result = result.replaceAll("\\{" + i + "\\}", value);
	        }
	    }
    }
    return result;
}

Array.prototype.removeByIndex = function(val) {
	var index = val;
	if (index > -1) {
		this.splice(index, 1);
	}
};
window.console = window.console || {};
if (typeof console.log=="undefined"){
	if (typeof opera=="undefined"){
		console.log=function(){};
	}
	else{
		console.log=opera.postError;
	}
}
/*
if (typeof Object.getOwnPropertyNames=="undefined"){
	Object.prototype.getOwnPropertyNames=function(obj){
		var arr = [];
		for (var k in obj) {
		    if (obj.hasOwnProperty(k)) 
		        arr.push(k); 
		}
		return arr;
	}
}*/
$.extend({
	objclone:function(o){
		return $.extend({},o);
	},
	event_stop:function(event){
		if (event.stopPropagation){
			event.stopPropagation();
		}
		else{
			event.cancelBubble=true;
		}
	},
	event_prevent:function(event){
		if (event.preventDefault){
			  event.preventDefault();
		}
		else{
		   event.returnValue=false;
		}
	},
	isDateInputSupported :function(){
		var elem = document.createElement('input');
		elem.setAttribute('type','date');
		elem.value = 'foo';
		return (elem.type == 'date' && elem.value != 'foo');
		}
    ,

	deskNotice: function(){
        if (!requestPermission()) return;
        //注意，这才是真正用到的函数哦
        return function(msg,url,detail,icon){
            requestPermission();
            if( Notification && Notification.permission === "granted" ){
                var notification = new Notification(
                    msg,
                    {
                        icon: icon ,//|| 'http://yuanoook.com/wp-content/uploads/2015/05/cropped-a5ed12b00e23b1e471e615f9aff178c1f9af9158-192x192.jpg',
                        body: detail || "点击查看详情",
                    }
                );
                notification.onclick = function(){
                	if(url==null)return;
                    window.open( url );
                };
            }
        }
        function requestPermission(){
        	if (typeof Notification=="undefined"){
        		return false;
        	}
            !Notification && alert('你的浏览器不支持桌面提醒，请使用 Chrome 浏览器！');
            Notification && Notification.permission !== "granted" && Notification.requestPermission();
            return true;
        }
    }(),
	escapeHtml:function (text) {
		 if (text==null) return "";
		  /*return text
		      .replace(/&/g, "&amp;")
		      .replace(/</g, "&lt;")
		      .replace(/>/g, "&gt;")
		      .replace(/"/g, "&quot;")
		      .replace(/'/g, "&#039;");*/
		 var map = {
				    '&': '&amp;',
				    '<': '&lt;',
				    '>': '&gt;',
				    '"': '&quot;',
				    ' ': '&nbsp;',
				    '\n': '<br/>',
				    "'": '&#039;'
				  };
		 		try{
				  return text.replace(/[&<>"']/g, function(m) { 
					  return map[m]; 
				  }).replaceAll("\n","<br/>").replaceAll(" ","&nbsp;");
		 		}
		 		catch (e){
		 			console.log("convert to html failed, source:"+text);
		 		}	
		},
   getWidgetPosition:function(widget){
		var ret={};
		ret.left=widget.offsetLeft;
		ret.top=widget.offsetTop;
		while (widget= widget.offsetParent) {
			ret.left += widget.offsetLeft;
			ret.top += widget.offsetTop;
		}
		return ret;
	},
	getRowObjByIndex:function(idx){
		return $('#row'+idx+'grid');
	},
	form2Obj:function (pvFormID){
		var w_formp={};			
		$.each($("#"+pvFormID).serializeArray(),function(i, item){
			w_formp[item.name] = item.value;
		});		
		return w_formp;
	},
	toThousands:function (s,n) {
		 if (n==null){
			 n=0;
		 }
		 else{
			 n = n > 0 && n <= 20 ? n : 2;
		 }
		    s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";  
		    var l = s.split(".")[0].split("").reverse(), r = s.split(".")[1];  
		    t = "";  
		    for (i = 0; i < l.length; i++) {  
		        t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");  
		    }  
		    if (n==0){
		    	return t.split("").reverse().join("") ;
		    }
		    else
		    return t.split("").reverse().join("") + "." + r;  
	}
});

var delay = (function(){
	  var timer = 0;
	  return function(callback, ms){
		clearTimeout (timer);
		timer = setTimeout(callback, ms);
	  };
	})();	

$(function() {
	//LOADING.init();
	$(".blockSorting").click(function(event) {
		event.stopPropagation();
	});
	if (/MSIE 9|MSIE 8|MSIE 7|MSIE 6/g.test(navigator.userAgent)) {
		$('[data-placeholder]').focus(function() {
		  var input = $(this);
		  if (input.val() == input.attr('data-placeholder')) {
			input.val('');
			input.removeClass('data-placeholder');
		  }
		}).blur(function() {
		  var input = $(this);
		  if (input.val() == '' || input.val() == input.attr('data-placeholder')) {
			input.addClass('data-placeholder');
			input.val(input.attr('data-placeholder'));
		  }
		}).blur();
	}
	
	
});
/*
$(document).ready(function(){
	try{
	$[ "ui" ][ "autocomplete" ].prototype["_renderItem"] = function( ul, item) {
		return $( "<li></li>" )
		.data( "item.autocomplete", item )
		.append( $( "<a></a>" ).html( item.label ) )
		.appendTo( ul );
	};
	}
	catch (e){}
}
);*/

(function() {

    var beforePrint = function() {
        console.log('Functionality to run before printing.');
        if (typeof window.onbeforeprint!="undefined"){
        	window.onbeforeprint();
        }
    };

    var afterPrint = function() {
        console.log('Functionality to run after printing');
        if (typeof window.onafterprint!="undefined"){
        	window.onafterprint();
        }
    };

    if (window.matchMedia) {
        var mediaQueryList = window.matchMedia('print');
        mediaQueryList.addListener && mediaQueryList.addListener(function(mql) {
            if (mql.matches) {
                beforePrint();
            } else {
                afterPrint();
            }
        });
    }

    /*window.onbeforeprint = beforePrint;
    window.onafterprint = afterPrint;*/

}());

(function($, window, document,undefined){
	/***
	 * console.log(window.browser);
console.log($.isIE());
console.log($.isChrome());
	 */
	  if(!window.browser){
	      
	    var userAgent = navigator.userAgent.toLowerCase(),uaMatch;
	    window.browser = {}
	      
	    /**
	     * 判断是否为ie
	     */
	    function isIE(){
	      return ("ActiveXObject" in window);
	    }
	    /**
	     * 判断是否为谷歌浏览器
	     */
	    if(!uaMatch){
	      uaMatch = userAgent.match(/chrome\/([\d.]+)/);
	      if(uaMatch!=null){
	        window.browser['name'] = 'chrome';
	        window.browser['version'] = uaMatch[1];
	      }
	    }
	    /**
	     * 判断是否为火狐浏览器
	     */
	    if(!uaMatch){
	      uaMatch = userAgent.match(/firefox\/([\d.]+)/);
	      if(uaMatch!=null){
	        window.browser['name'] = 'firefox';
	        window.browser['version'] = uaMatch[1];
	      }
	    }
	    /**
	     * 判断是否为opera浏览器
	     */
	    if(!uaMatch){
	      uaMatch = userAgent.match(/opera.([\d.]+)/);
	      if(uaMatch!=null){
	        window.browser['name'] = 'opera';
	        window.browser['version'] = uaMatch[1];
	      }
	    }
	    /**
	     * 判断是否为Safari浏览器
	     */
	    if(!uaMatch){
	      uaMatch = userAgent.match(/safari\/([\d.]+)/);
	      if(uaMatch!=null){
	        window.browser['name'] = 'safari';
	        window.browser['version'] = uaMatch[1];
	      }
	    }
	    /**
	     * 最后判断是否为IE
	     */
	    if(!uaMatch){
	      if(userAgent.match(/msie ([\d.]+)/)!=null){
	        uaMatch = userAgent.match(/msie ([\d.]+)/);
	        window.browser['name'] = 'ie';
	        window.browser['version'] = uaMatch[1];
	      }else{
	        /**
	         * IE10
	         */
	        if(isIE() && !!document.attachEvent && (function(){"use strict";return !this;}())){
	          window.browser['name'] = 'ie';
	          window.browser['version'] = '10';
	        }
	        /**
	         * IE11
	         */
	        if(isIE() && !document.attachEvent){
	          window.browser['name'] = 'ie';
	          window.browser['version'] = '11';
	        }
	      }
	    }
	  
	    /**
	     * 注册判断方法
	     */
	    if(!$.isIE){
	      $.extend({
	        isIE:function(){
	          return (window.browser.name == 'ie');
	        }
	      });
	    }
	    if(!$.isChrome){
	      $.extend({
	        isChrome:function(){
	          return (window.browser.name == 'chrome');
	        }
	      });
	    }
	    if(!$.isFirefox){
	      $.extend({
	        isFirefox:function(){
	          return (window.browser.name == 'firefox');
	        }
	      });
	    }
	    if(!$.isOpera){
	      $.extend({
	        isOpera:function(){
	          return (window.browser.name == 'opera');
	        }
	      });
	    }
	    if(!$.isSafari){
	      $.extend({
	        isSafari:function(){
	          return (window.browser.name == 'safari');
	        }
	      });
	    }
	  }
	})(jQuery, window, document);

/*
LOADING=(function (){
	var _this={};
	_this.loadingvisible=false;
	_this.divHtml="<div id='div_loading' style='opacity:0.5;filter:Alpha(Opacity=50);background:#666666 url(./images/loader.gif) no-repeat center center;position:fixed;top:0;left:0;width:100%;height:100%;z-index:500000'></div>";
	var m_divObj=null;
	var m_tm;
	_this.init=function(){
		$("#div_loading").remove();
		$(LOADING.divHtml).appendTo($(document.body));
		m_divObj=$("#div_loading");
		LOADING.hideloading();
	};
	var m_needHide=false;
	var m_show=function(){
		if (m_needHide) return;
		m_divObj.show();
		LOADING.loadingvisible=true;
	};
	_this.showloading=function(delay){
		if (typeof delay=="undefined"){
			delay=1500;
		}
		//$(w_div).appendTo(document);
		//LOADING.divObj.attr({"visibility":"visible"});
		m_needHide=false;
		if (delay){
			m_tm=setTimeout(m_show,delay);
		}
		else{
			m_show();
		}
	};
	var m_hide=function(){
		    m_needHide=true;
			clearTimeout(m_tm);
			m_divObj.hide();
			LOADING.loadingvisible=false;
	};
	_this.hideloading=function(){
		//$(w_div).appendTo(document);
		//LOADING.divObj.attr({"visibility":"hidden"});
		m_hide();
		setTimeout(m_hide,600);
	}
	return _this;
})();

 */
function showErrorToast(pvMsg) {
    $().toastmessage('showErrorToast', pvMsg);
}
function showSuccessToast(pvMsg) {
   //change to display a big icon only !!!
   $().toastmessage('showSuccessToast', pvMsg);
	//showAccept(1000);	
}
function showErrorMessage(pvMsg,pvWidget){
	if (pvWidget==null){
		pvWidget=$("[name='div_result']");
	}
	pvWidget.html(pvMsg).removeAttr("class").addClass("alertx alertx-error").show("fast").click(function(){
		$(this).hide("fast");
	});
}
function showWarningMessage(pvMsg,pvWidget){
	pvWidget.html(pvMsg).removeAttr("class").attr({"data-dismiss":"alert"}).addClass("alert alert-warning").show("fast");
}
function showSuccessMessage(pvMsg,pvWidget){
	pvWidget.html(pvMsg).removeAttr("class").attr({"data-dismiss":"alert"}).addClass("alert alert-success").show("fast");
}
var m_accept=null;
function showAccept(pvKeepTm){
	if (! m_accept){
		m_accept=$('<img src="./media/image/accpet.png"  style="margin-left: -150px;margin-top: -150px; z-index:600000;text-align: center;position: absolute;left: 50%;top: 50%;display:none;" />').appendTo("body");
	}
	m_accept.fadeIn();
	setTimeout(function()
			{
				m_accept.fadeOut();
			},pvKeepTm);
}


function afterHook(pvWidget){ 
	
	 pvWidget.click(function() {
			$(this).autocomplete( "search", $(this).val() );
		}).mouseover(function() {
			$(this).addClass("arrowdown") ;
		}).mouseout(function() {
			$(this).removeClass("arrowdown") ;
		}).mousemove(function(event) {
			var rect = this.getBoundingClientRect();
			if (event.clientX >= rect.right - 20) {
				$(this).css("cursor","default");
			} else {
				$(this).css("cursor","");
			}
		}) .keyup(function(e) {
			$(this).val($(this).val().toUpperCase());
			if (e.keyCode === 13) {
				$(this).closest('form').trigger('submit');
			}
		});
}

/*data:JSON.stringify($.extend(options.onFetch(),m_status)),*/
function setToAjax(){
$.ajaxSetup({	  
	  global: false,
	  type: "POST",
	  dataType: "json",	  
	  contentType:"application/x-www-form-urlencoded"
	});
}
function postJSON(url,data,pvSuccessFun,pvNotCvt){
	setToAjax();
	 $.post(url,pvNotCvt?data:JSON.stringify(data),function(data){
		 pvSuccessFun(data);
	 });	  
} 



function cvTm(tm,dt,after){
	if (tm<0){
		return cvTm(- tm,dt,true);
	}
	var lvsuffix="前";
	if (after){
		lvsuffix="后";
	}
	if (tm<1){
		return "刚刚";
	}
	if (tm<60){
		return Math.round(tm)+"分钟"+lvsuffix;	
	}			
	var lvH=Math.floor(tm/60);
	if (lvH<24){
		return lvH+"小时"+Math.round(tm-lvH*60)+"分钟"+lvsuffix;
	}
	var lvD=Math.round(tm/60/24);
	if (lvD<4){
		  return lvD+"天"+lvsuffix;
	}
	else{
		return (new Date(dt)).format('yyyy年MM月dd日');
	}
}

function getMostTopZIndex(){
	var highest = 0;
	$("div").each(function() {
	    var current = parseInt($(this).css("z-index"), 10);
	    if(current && highest < current) highest = current;
	});
	return highest ;
}

